// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    banners: [],
    recommendCourses: [],
    hotAcupoints: [],
    reflexZones: [],
    userStats: {
      learnDays: 0,
      courseCount: 0,
      acupointCount: 0
    },
    // 3D展示相关
    show3DView: false,
    current3DBodyImage: 'http://39.97.48.169:9000/zhongyi/e861db718e094fcab304882b42fdde31.png',
    zoomLevel3D: 1,
    rotationX3D: 0,
    rotationY3D: 0,
    // 触摸相关
    touchStartX: 0,
    touchStartY: 0,
    lastTouchX: 0,
    lastTouchY: 0,
    isRotating: false
  },

  onLoad() {
    console.log('首页开始加载数据')
    this.loadHomeData()
  },

  onShow() {
    console.log('首页 onShow 被调用')
    console.log('当前 hotAcupoints 数据:', this.data.hotAcupoints)
    console.log('hotAcupoints 长度:', this.data.hotAcupoints ? this.data.hotAcupoints.length : 'undefined')
    this.loadUserStats()
  },
  // 获取推荐课程数据
  getContent() {
    wx.request({
      url: 'http://localhost:8081/contentChapter/getCont',
      method: "GET",
      success: (res) => {
        console.log('推荐课程数据:', res.data)
        if (res.data && res.data.length > 0) {
          // 转换API数据格式为页面需要的格式
          const recommendCourses = res.data.map(course => ({
            id: course.id,
            title: course.title,
            cover: course.cover,
            type: course.type,
            typeText: course.type === 'course' ? '课程' : '其他',
            duration: course.duration,
            isFree: course.isFree === 1,
            price: course.price,
            viewCount: course.viewCount,
            saleCount: course.saleCount,
            intro: course.intro,
            lecturer: course.lecturer,
            organization: course.organization,
            chapterList: course.chapterList
          }))
          
          this.setData({
            recommendCourses: recommendCourses
          })
        }
      },
      fail: (err) => {
        console.error('获取推荐课程失败:', err)
        // 使用模拟数据作为备选
        const mockCourses = [
          {
            id: 1,
            title: '中医基础理论',
            cover: 'https://via.placeholder.com/500x300/3cc51f/ffffff?text=中医基础',
            type: 'course',
            typeText: '课程',
            duration: 120,
            isFree: true,
            price: 0,
            viewCount: 1250,
            saleCount: 800,
            intro: '系统学习中医基础理论，掌握中医核心概念'
          }
        ]
        this.setData({
          recommendCourses: mockCourses
        })
      }
    })
  },
  // 加载首页数据
  loadHomeData() {
    console.log('开始加载首页数据')
    
    try {
      // 轮播图数据 - 中医传统主题
      const banners = [
        {
          id: 1,
          imageUrl: '/images/u132.png'
        },
        {
          id: 2,
          imageUrl: '/images/u9312.png'
        },
        {
          id: 3,
          imageUrl: '/images/u9313.png'
        }
      ]

      // 人体穴位图像数据 - 穴位图形式
      const hotAcupoints = [
        {
          id: 1,
          imageTitle: '成人穴位图',
          imageUrl: 'http://39.97.48.169:9000/zhongyi/e861db718e094fcab304882b42fdde31.png',
          imageCategory: 1,
          categoryText: '成人',
          bodyPosition: '全身',
          isFree: true,
          price: 0,
          viewCount: 3200,
          description: '成人全身穴位图，包含主要经络和穴位',
          acupointCount: 365,
          coordinates: { x: 50, y: 18 },
          isActive: false
        },
        {
          id: 2,
          imageTitle: '儿童穴位图',
          imageUrl: 'http://39.97.48.169:9000/zhongyi/u7348.png',
          imageCategory: 2,
          categoryText: '儿童',
          bodyPosition: '全身',
          isFree: false,
          price: 39,
          viewCount: 2800,
          description: '儿童专用穴位图，适合小儿推拿',
          acupointCount: 200,
          coordinates: { x: 50, y: 30 },
          isActive: false
        },
        {
          id: 3,
          imageTitle: '成人背部穴位',
          imageUrl: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=500&h=600&fit=crop&crop=center',
          imageCategory: 1,
          categoryText: '成人',
          bodyPosition: '背部',
          isFree: true,
          price: 0,
          viewCount: 2500,
          description: '成人背部穴位图，重点标注背部经络',
          acupointCount: 120,
          coordinates: { x: 48, y: 72 },
          isActive: false
        }
      ]

      // 反射区数据
      const reflexZones = [
        {
          id: 1,
          title: '足部肾脏反射区',
          imageUrl: 'https://images.unsplash.com/photo-1559757148-5c350d0d3c56?w=500&h=300&fit=crop&crop=center',
          isFree: true,
          price: 0,
          description: '足部肾脏反射区，通过足部按摩调理身体'
        },
        {
          id: 2,
          title: '手部心脏反射区',
          imageUrl: 'https://images.unsplash.com/photo-1571019613454-1cb2f99b2d8b?w=500&h=300&fit=crop&crop=center',
          isFree: true,
          price: 0,
          description: '耳迷根反射区，调节迷走神经功能'
        },
        {
          id: 3,
          title: '耳部脾胃反射区',
          imageUrl: 'https://images.unsplash.com/photo-1544367567-0f2fcb009e0b?w=500&h=300&fit=crop&crop=center',
          isFree: false,
          price: 29,
          description: '足底反射区，全身器官的反射点'
        }
      ]

      console.log('穴位数据准备完成，数量:', hotAcupoints.length)
      console.log('穴位数据详情:', hotAcupoints)

      // 设置轮播图、热门穴位和反射区数据
      // 只显示前3个热门穴位
      const limitedHotAcupoints = hotAcupoints.slice(0, 3)
      
      this.setData({
        banners,
        hotAcupoints: limitedHotAcupoints,
        reflexZones
      })
      
      console.log('首页数据设置完成')
      console.log('设置后的 hotAcupoints:', this.data.hotAcupoints)
      console.log('设置后的 hotAcupoints 长度:', this.data.hotAcupoints.length)
      console.log('第一个穴位数据:', this.data.hotAcupoints[0])
      
      // 延迟验证数据是否正确设置
      setTimeout(() => {
        console.log('延迟验证 - hotAcupoints:', this.data.hotAcupoints)
        console.log('延迟验证 - 第一个穴位:', this.data.hotAcupoints[0])
      }, 100)
      
      // 获取推荐课程数据
      this.getContent()
    } catch (error) {
      console.error('加载首页数据失败:', error)
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      })
    }
  },

  // 加载用户统计数据
  loadUserStats() {
    // 模拟用户统计数据
    const userStats = {
      learnDays: 15,
      courseCount: 8,
      acupointCount: 12
    }
    this.setData({ userStats })
  },

  // 导航到指定页面
  navigateTo(e) {
    const url = e.currentTarget.dataset.url
    console.log('导航到页面:', url)
    
    // 检查是否是tabBar页面，使用switchTab
    const tabBarPages = [
      '/pages/index/index',
      '/pages/courses/courses', 
      '/pages/ai/ai',
      '/pages/mall/mall',
      '/pages/user/user'
    ]
    
    if (tabBarPages.includes(url)) {
      console.log('使用switchTab跳转到tabBar页面:', url)
      wx.switchTab({
        url: url
      })
    } else {
      console.log('使用navigateTo跳转到普通页面:', url)
      wx.navigateTo({
        url: url
      })
    }
  },

    // 功能卡片点击事件
    onFunctionTap(e) {
      const functionType = e.currentTarget.dataset.type
      console.log('功能卡片点击:', functionType)
      
      // 跳转到技术详情页面
      wx.navigateTo({
        url: `/pages/technique-detail/technique-detail?type=${functionType}`
      })
    },

  // 搜索点击事件
  onSearchTap() {
    console.log('点击搜索')
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  // 扫码点击事件
  onScanTap() {
    console.log('点击扫码')
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res)
        wx.showToast({
          title: '扫码成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.log('扫码失败:', err)
      }
    })
  },

  // 视频播放记录点击事件
  onVideoHistoryTap() {
    console.log('点击视频播放记录')
    wx.navigateTo({
      url: '/pages/video-history/video-history'
    })
  },

  // 课程点击事件
  onCourseTap(e) {
    const courseId = e.currentTarget.dataset.id
    console.log('课程点击，ID:', courseId)
    
    if (courseId) {
      wx.navigateTo({
        url: `/pages/course-detail/course-detail?id=${courseId}`
      })
    } else {
      console.error('课程ID无效:', courseId)
      wx.showToast({
        title: '课程数据错误',
        icon: 'none'
      })
    }
  },

  // 穴位点击事件
  onAcupointTap(e) {
    console.log('=== 穴位点击事件开始 ===')
    console.log('事件对象:', e)
    console.log('事件当前目标:', e.currentTarget)
    console.log('事件当前目标dataset:', e.currentTarget ? e.currentTarget.dataset : 'currentTarget不存在')
    
    // 从dataset获取穴位数据
    const acupoint = e.currentTarget.dataset.acupoint
    console.log('从dataset获取的穴位数据:', acupoint)
    console.log('穴位数据类型:', typeof acupoint)
    
    if (!acupoint || !acupoint.id) {
      console.error('穴位数据无效:', acupoint)
      console.error('详细错误信息:')
      console.error('- e.currentTarget 存在:', !!e.currentTarget)
      console.error('- e.currentTarget.dataset 存在:', !!(e.currentTarget && e.currentTarget.dataset))
      console.error('- e.currentTarget.dataset.acupoint 存在:', !!(e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.acupoint))
      console.error('- acupoint 存在:', !!acupoint)
      console.error('- acupoint.id 存在:', !!(acupoint && acupoint.id))
      
      wx.showToast({
        title: '穴位数据错误',
        icon: 'none',
        duration: 3000
      })
      return
    }
    
    console.log('跳转到穴位详情页，ID:', acupoint.id)
    wx.navigateTo({
      url: `/pages/acupoint-detail/acupoint-detail?id=${acupoint.id}`,
      success: () => {
        console.log('成功跳转到穴位详情页')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
    console.log('=== 穴位点击事件结束 ===')
  },

  // 反射区点击事件
  onReflexTap(e) {
    const reflexId = e.currentTarget.dataset.id
    console.log('反射区点击，ID:', reflexId)
    
    if (reflexId) {
      wx.navigateTo({
        url: `/pages/reflex-detail/reflex-detail?id=${reflexId}`
      })
    } else {
      console.error('反射区ID无效:', reflexId)
      wx.showToast({
        title: '反射区数据错误',
        icon: 'none'
      })
    }
  },

  // 轮播图点击事件
  onBannerTap(e) {
    const bannerId = e.currentTarget.dataset.id
    let url = ''
    
    switch(bannerId) {
      case 1:
        url = '/pages/courses/courses'
        break
      case 2:
        url = '/pages/acupoints/acupoints'
        break
      case 3:
        url = '/pages/courses/courses'
        break
      default:
        url = '/pages/courses/courses'
    }
    
    wx.switchTab({
      url: url
    })
  },

  // 跳转到穴位展示页面
  goTo3DAcupoints() {
    console.log('跳转到穴位展示页面')
    wx.navigateTo({
      url: '/pages/acupoints/acupoints',
      success: () => {
        console.log('成功跳转到穴位展示页面')
      },
      fail: (err) => {
        console.error('跳转失败:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  // 切换3D视图
  toggle3DView() {
    console.log('切换3D视图')
    this.setData({
      show3DView: !this.data.show3DView
    })
  },

  // 重置3D视角
  reset3DView() {
    console.log('重置3D视角')
    this.setData({
      zoomLevel3D: 1,
      rotationX3D: 0,
      rotationY3D: 0
    })
  },

  // 选择3D穴位
  select3DAcupoint(e) {
    const acupoint = e.currentTarget.dataset.acupoint
    console.log('选择3D穴位:', acupoint)
    
    if (acupoint) {
      // 重置所有穴位的激活状态
      const hotAcupoints = this.data.hotAcupoints.map(item => ({
        ...item,
        isActive: item.id === acupoint.id
      }))
      
      this.setData({
        hotAcupoints: hotAcupoints
      })
    }
  },

  // 3D穴位点击事件
  on3DAcupointTap(e) {
    const acupoint = e.currentTarget.dataset.acupoint
    console.log('3D穴位点击:', acupoint)
    
    if (acupoint) {
      // 重置所有穴位的激活状态
      const hotAcupoints = this.data.hotAcupoints.map(item => ({
        ...item,
        isActive: item.id === acupoint.id
      }))
      
      this.setData({
        hotAcupoints: hotAcupoints
      })
      
      // 显示穴位详情
      wx.showModal({
        title: acupoint.imageTitle,
        content: `${acupoint.description}\n\n位置：${acupoint.bodyPosition}\n经络：${acupoint.categoryText}`,
        showCancel: true,
        cancelText: '关闭',
        confirmText: '查看详情',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: `/pages/acupoint-detail/acupoint-detail?id=${acupoint.id}`
            })
          }
        }
      })
    }
  },

  // 3D触摸开始
  on3DTouchStart(e) {
    const touch = e.touches[0]
    this.setData({
      touchStartX: touch.clientX,
      touchStartY: touch.clientY,
      lastTouchX: touch.clientX,
      lastTouchY: touch.clientY,
      isRotating: true
    })
  },

  // 3D触摸移动
  on3DTouchMove(e) {
    if (!this.data.isRotating) return
    
    const touch = e.touches[0]
    const deltaX = touch.clientX - this.data.lastTouchX
    const deltaY = touch.clientY - this.data.lastTouchY
    
    // 计算旋转角度
    const rotationY = this.data.rotationY3D + deltaX * 0.5
    const rotationX = this.data.rotationX3D - deltaY * 0.5
    
    this.setData({
      rotationY3D: rotationY,
      rotationX3D: Math.max(-30, Math.min(30, rotationX)), // 限制X轴旋转范围
      lastTouchX: touch.clientX,
      lastTouchY: touch.clientY
    })
  },

  // 3D触摸结束
  on3DTouchEnd(e) {
    this.setData({
      isRotating: false
    })
  }
})
